<script setup lang="ts">
import { useAuthStore } from '@/store'
import { adminApi } from '@/service/api/bizhi'
import { local } from '@/utils'

const authStore = useAuthStore()
const { userInfo } = authStore

// 个人信息表单
const profileFormRef = ref()
const profileForm = ref({
  name: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: ''
})

// 密码修改表单
const passwordFormRef = ref()
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 加载状态
const profileLoading = ref(false)
const passwordLoading = ref(false)

// 表单验证规则
const profileRules = {
  name: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      min: 1,
      max: 100,
      message: '姓名长度必须在1-100个字符之间',
      trigger: 'blur',
    }
  ],
  nickname: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      min: 1,
      max: 100,
      message: '昵称长度必须在1-100个字符之间',
      trigger: 'blur',
    }
  ],
  email: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
      message: '请输入正确的邮箱格式',
      trigger: 'blur',
    }
  ],
  phone: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur',
    }
  ],
  avatar: [
    {
      required: false,
      trigger: 'blur',
    },
    {
      pattern: /^https?:\/\/.+/,
      message: '头像必须是有效的URL地址',
      trigger: 'blur',
    }
  ]
}

const passwordRules = {
  currentPassword: [
    {
      required: true,
      message: '请输入当前密码',
      trigger: 'blur',
    }
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur',
    },
    {
      min: 6,
      max: 50,
      message: '新密码长度必须在6-50个字符之间',
      trigger: 'blur',
    },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,
      message: '新密码必须包含至少一个字母和一个数字',
      trigger: 'blur',
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur',
    },
    {
      validator: (rule: any, value: string) => {
        return value === passwordForm.value.newPassword
      },
      message: '两次输入的密码不一致',
      trigger: ['blur', 'input'],
    }
  ]
}

// 初始化表单数据
onMounted(() => {
  if (userInfo) {
    profileForm.value = {
      name: userInfo.name || '',
      nickname: userInfo.nickname || '',
      email: userInfo.email || '',
      phone: userInfo.phone || '',
      avatar: userInfo.avatar || ''
    }
  }
})

// 更新个人信息
const handleUpdateProfile = async () => {
  try {
    await profileFormRef.value?.validate()
    profileLoading.value = true

    // 过滤空值
    const updateData = Object.fromEntries(
      Object.entries(profileForm.value).filter(([_, value]) => value !== '')
    )
    const response = await adminApi.updateProfile(updateData)

    if (response.code === 200) {
      // 更新store中的用户信息
      authStore.userInfo = { ...authStore.userInfo, ...response.data.user }
      // 同时更新本地存储
      local.set('userInfo', authStore.userInfo)
      window.$message.success('个人信息更新成功')
    }
  } catch (error: any) {
    console.error('更新个人信息失败:', error)

    if (error?.response?.data?.message) {
      window.$message.error(error.response.data.message)
    } else if (error?.response?.data?.errors) {
      // 处理验证错误
      const errors = error.response.data.errors
      const errorMessages = errors.map((err: any) => err.msg || err.message).join(', ')
      window.$message.error(`验证失败: ${errorMessages}`)
    } else {
      window.$message.error('更新失败，请检查网络连接后重试')
    }
  } finally {
    profileLoading.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value?.validate()
    passwordLoading.value = true

    const response = await adminApi.changePassword(passwordForm.value)

    if (response.code === 200) {
      window.$message.success('密码修改成功，请妥善保管新密码')
      // 清空表单
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
      // 重置表单验证状态
      passwordFormRef.value?.restoreValidation()
    }
  } catch (error: any) {
    console.error('修改密码失败:', error)

    if (error?.response?.data?.message) {
      window.$message.error(error.response.data.message)
    } else if (error?.response?.data?.errors) {
      // 处理验证错误
      const errors = error.response.data.errors
      const errorMessages = errors.map((err: any) => err.msg || err.message).join(', ')
      window.$message.error(`验证失败: ${errorMessages}`)
    } else {
      window.$message.error('密码修改失败，请检查网络连接后重试')
    }
  } finally {
    passwordLoading.value = false
  }
}

// 重置个人信息表单
const handleResetProfile = () => {
  if (userInfo) {
    profileForm.value = {
      name: userInfo.name || '',
      nickname: userInfo.nickname || '',
      email: userInfo.email || '',
      phone: userInfo.phone || '',
      avatar: userInfo.avatar || ''
    }
  }
}
</script>

<template>
  <div class="user-center">
    <n-space vertical :size="24">
      <!-- 个人信息展示 -->
      <n-card title="个人信息">
        <n-space size="large" align="center">
          <n-avatar round :size="120" :src="userInfo?.avatar || '/default-avatar.png'" />

          <div class="user-info">
            <n-descriptions label-placement="left" :column="2" size="large">
              <n-descriptions-item label="用户ID">
                {{ userInfo?.id }}
              </n-descriptions-item>
              <n-descriptions-item label="手机号">
                {{ userInfo?.phone }}
              </n-descriptions-item>
              <n-descriptions-item label="姓名">
                {{ userInfo?.name || '未设置' }}
              </n-descriptions-item>
              <n-descriptions-item label="昵称">
                {{ userInfo?.nickname || '未设置' }}
              </n-descriptions-item>
              <n-descriptions-item label="邮箱">
                {{ userInfo?.email || '未设置' }}
              </n-descriptions-item>
              <n-descriptions-item label="注册时间">
                {{ userInfo?.created_at ? new Date(userInfo.created_at).toLocaleDateString() : '-' }}
              </n-descriptions-item>
            </n-descriptions>
          </div>
        </n-space>
      </n-card>

      <!-- 个人信息编辑 -->
      <n-card title="编辑个人信息">
        <n-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-placement="left"
          :label-width="100"
          class="max-w-600px"
        >
          <n-form-item label="姓名" path="name">
            <n-input
              v-model:value="profileForm.name"
              placeholder="请输入真实姓名"
              clearable
            />
          </n-form-item>

          <n-form-item label="昵称" path="nickname">
            <n-input
              v-model:value="profileForm.nickname"
              placeholder="请输入昵称"
              clearable
            />
          </n-form-item>

          <n-form-item label="邮箱" path="email">
            <n-input
              v-model:value="profileForm.email"
              placeholder="请输入邮箱地址"
              clearable
            />
          </n-form-item>

          <n-form-item label="手机号" path="phone">
            <n-input
              v-model:value="profileForm.phone"
              placeholder="请输入手机号"
              clearable
            />
          </n-form-item>

          <n-form-item label="头像URL" path="avatar">
            <n-input
              v-model:value="profileForm.avatar"
              placeholder="请输入头像链接"
              clearable
            />
          </n-form-item>

          <n-form-item>
            <n-space>
              <n-button
                type="primary"
                :loading="profileLoading"
                @click="handleUpdateProfile"
              >
                保存修改
              </n-button>
              <n-button @click="handleResetProfile">
                重置
              </n-button>
            </n-space>
          </n-form-item>
        </n-form>
      </n-card>

      <!-- 修改密码 -->
      <n-card title="修改密码">
        <n-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-placement="left"
          :label-width="100"
          class="max-w-600px"
        >
          <n-form-item label="当前密码" path="currentPassword">
            <n-input
              v-model:value="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password-on="click"
              clearable
            />
          </n-form-item>

          <n-form-item label="新密码" path="newPassword">
            <n-input
              v-model:value="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码（至少6位）"
              show-password-on="click"
              clearable
            />
          </n-form-item>

          <n-form-item label="确认新密码" path="confirmPassword">
            <n-input
              v-model:value="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password-on="click"
              clearable
            />
          </n-form-item>

          <n-form-item>
            <n-button
              type="primary"
              :loading="passwordLoading"
              @click="handleChangePassword"
            >
              修改密码
            </n-button>
          </n-form-item>
        </n-form>
      </n-card>
    </n-space>
  </div>
</template>

<style scoped>
.user-center {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.user-info {
  flex: 1;
}

.max-w-600px {
  max-width: 600px;
}
</style>
